package cn.bugstack.springframework.beans.factory.support;

import cn.bugstack.springframework.beans.BeansException;
import cn.bugstack.springframework.beans.factory.config.BeanDefinition;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;


/**
 * 用cglib动态来创建bean对象,cglib代理的对象不需要实现接口,jdk的代理对象需要实现接口
 * @author oyz
 */
public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy{


    @Override
    public Object instantiate(BeanDefinition beanDefinition, String beanName, Constructor cor, Object[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, BeansException, Exception {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });
        if(null == cor){
            return enhancer.create();
        }

        return enhancer.create(cor.getParameterTypes(),args);
    }
}
